package com.tangyuan.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class IPGeolocation {

    private static final String API_URL = "https://restapi.amap.com/v3/ip";
    private static final String API_KEY = "2d87d82d4b9e865429000f789a3d06b5";

    public static void main(String[] args) {
        String ipAddress = "27.193.87.203";
        String result = getGeolocation(ipAddress);
        System.out.println(result);
    }

    public static String getGeolocation(String ipAddress) {
        try {
            String encodedIp = URLEncoder.encode(ipAddress, StandardCharsets.UTF_8.toString());
            URL url = new URL(API_URL + "?key=" + API_KEY + "&ip=" + encodedIp);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                reader.close();
                JsonParser parser = new JsonParser();
                JsonObject root = parser.parse(response.toString()).getAsJsonObject();

                String infocode = root.get("infocode").getAsString();
                if ("10000".equals(infocode)) { // 检查infocode是否表示成功
                    JsonElement cityElement = root.get("city");
                    if (cityElement != null && cityElement.isJsonPrimitive() && cityElement.getAsJsonPrimitive().isString()) {
                        String city = cityElement.getAsString();
                        return city;
                        // 这里可以安全地使用city变量
                    } else {
                        log.error("Request failed with city: "+ cityElement.toString());
                        return null;
                    }
                } else {
                    log.error("Request failed with infocode: "+ infocode);
                    return null;
                }
            } else {
                log.error("Failed to retrieve data from AMap API. Response code"+ responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}